package com.oop234.spi;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.concurrent.CopyOnWriteArrayList;

import com.oop234.spi.exception.ParserNotFoundException;

public class SongParseUtils {

    private SongParseUtils() {
    }

    private static final CopyOnWriteArrayList<SongParseService> REGISTERED_PARSERS = new CopyOnWriteArrayList<>();

    static {
        loadInitialParsers();
        System.out.println("SongParsers initialized.");
    }

    private static void loadInitialParsers() {
        // 1
        ServiceLoader<SongParseService> loadedParsers = ServiceLoader.load(SongParseService.class);
        // 2
        Iterator<SongParseService> driversIterator = loadedParsers.iterator();
        try{
            // 3
            while(driversIterator.hasNext()) {
                // 4
                SongParseService parser = driversIterator.next();
                REGISTERED_PARSERS.add(parser);
            }
        } catch(Throwable t) {
            //ignore
        }
    }

    /*public static synchronized void registerParser(SongParseService parser) {
        REGISTERED_PARSERS.add(parser);
    }*/

    public static Song parse(byte[] data) {
        // 结合多种数据结构可以有多种逻辑实现
        for (SongParseService parser: REGISTERED_PARSERS) {
            try {
                Song song = parser.parse(data);
                if (song != null) {
                    return song;
                }
            } catch (Exception e) {
                //ignore
            }
        }

        throw new ParserNotFoundException("Not found matched parser.");
    }

}
